package com.yunsom.testdemo.multiple_thread;

import com.yunsom.testdemo.multiple_thread.threadpooltest1.GetMonitorDataService;

import java.util.Calendar;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.tree.TreeNode;

/**
 * @author Xbao
 * @version 1.0
 * @description
 * es简介，原理，使用
 * kafka简介，原理，使用
 * 锁机制CAS  AQS
 * @date 2020/12/22 20:32
 */
public class MultiThreadTest {

  public static void main(String[] args) throws Exception {

    /**
    * 模拟高并发情况代码
    */
    final AtomicInteger atomicInteger = new AtomicInteger(0);
    final CountDownLatch countDownLatch = new CountDownLatch(1000); // 相当于计数器，当所有都准备好了，再一起执行，模仿多并发，保证并发量
    final CountDownLatch countDownLatch2 = new CountDownLatch(1000); // 保证所有线程执行完了再打印atomicInteger的值
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    try {
      for (int i = 0; i < 1000; i++) {
        executorService.submit(new Runnable() {
          @Override
          public void run() {
            try {
              countDownLatch.await(); //一直阻塞当前线程，直到计时器的值为0,保证同时并发
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            //每个线程增加1000次，每次加1
            for (int j = 0; j < 1000; j++) {
              atomicInteger.incrementAndGet();
            }
            countDownLatch2.countDown();
          }
        });
        countDownLatch.countDown();
      }

      countDownLatch2.await();// 保证所有线程执行完
      executorService.shutdown();
    } catch (Exception e){
      e.printStackTrace();
    }
    System.out.println("result:" + atomicInteger.get());

    ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
    for (int i = 0; i < 100; i++){
      int finalI = i;
      singleExecutor.submit(new Runnable() {
        @Override
        public void run() {
          try {
            Thread.sleep(new Random().nextInt(10) * 1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println("执行了" + finalI + "次");
          int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
          if(Objects.nonNull(1)){
            System.out.println("更新了一次数据库记录");
          } else {
            String lockKey = "device_test_multiple_add_lock" + "device1" + hour;
            try {
              System.out.println("新增了一次数据库记录");
            } catch (Exception e){
              System.out.println("写入数据库异常");
            }
          }
          System.out.println("更新了一次缓存记录");
        }
      });
    }

    System.out.println("end");

  }
}
